package com.hardware.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hardware.common.R;
import com.hardware.dto.OrdersDto;
import com.hardware.entity.*;
import com.hardware.service.OrderDetailService;
import com.hardware.service.OrderService;
import com.hardware.service.UserService;
import com.hardware.utils.ExcelUtils;
import javafx.util.converter.LocalDateStringConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hardware.utils.RedisConstants.CACHE_ORDER_KEY;

/**
 * 订单管理
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户通过前台 提交订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    @CacheEvict(value = CACHE_ORDER_KEY,allEntries = true)
    public R<String> submit(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 分布查询订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime) throws ParseException {
        String string = stringRedisTemplate.opsForValue().get("cache:order:" + page + '_' + pageSize);
        if(string != null){
            Page page1 = JSONUtil.toBean(string, Page.class);
            return R.success(page1);
        }
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> lqw1 = new LambdaQueryWrapper<>();
        lqw1.orderByDesc(Orders::getOrderTime);
        lqw1.eq(number !=null,Orders::getId,number);
        lqw1.ge(beginTime != null,Orders::getOrderTime,beginTime);
        lqw1.le(endTime != null,Orders::getOrderTime,endTime);

        orderService.page(pageInfo,lqw1);

        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");

        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> list = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(item,ordersDto);
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(lqw);
            ordersDto.setOrderDetails(orderDetails);

            Long userId = item.getUserId();//用户id
            //根据id查询分类对象
            User user = userService.getById(userId);
            if(user != null){
                ordersDto.setUserName(user.getName());
            }
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        String s = JSONUtil.toJsonStr(ordersDtoPage);
        stringRedisTemplate.opsForValue().set("cache:order:" + page + '_' + pageSize,s);
        return R.success(ordersDtoPage);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        return R.success("请选择商品");
    }

    /**
     * 更新订单状态
     * @param orders
     * @return
     */
    @PutMapping
    @CacheEvict(value = CACHE_ORDER_KEY,allEntries = true)
    public R<String> status(@RequestBody Orders orders){
        orderService.updateById(orders);
        return R.success("正在派送");
    }

    /**
     * 下载数据列表
     * @return
     */
    @GetMapping("/downloadReport")
    public R<ServletOutputStream> downloadReport(HttpServletResponse response) throws IOException {
        //返回的数据类型为文件xlsx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("Orders.xlsx".getBytes(),"iso8859-1");
        response.addHeader("Content-Disposition","attachment;fileName="+fileName);

        //生成报告的文件，然后传递到前端页面
        ByteArrayOutputStream os = orderService.getReport();
        //获取产生响应的流对象
        ServletOutputStream sos = response.getOutputStream();
        //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
        os.writeTo(sos);
        //将输出流刷新
        sos.flush();
        os.close();
        return R.success(sos);
    }
}
